package com.shujia.kafka

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

import java.util.Properties

object Demo4Tran {
  def main(args: Array[String]): Unit = {
    val properties = new Properties()
    //kafka 集群地址
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")

    //key和value的序列化类
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")

    properties.setProperty("transactional.id", "asdasdasd")

    //创建生产者，本质是创建和kafka的连接
    val producer = new KafkaProducer[String, String](properties)

    //1、初始化事务
    producer.initTransactions()
    //2、开启十五
    producer.beginTransaction()

    //发生数据
    producer.send(new ProducerRecord[String, String]("tran", "java"))

    Thread.sleep(10000)

    //发生数据
    producer.send(new ProducerRecord[String, String]("tran", "spark"))

    //提交事务
    producer.commitTransaction()

    producer.close()

    /**
     *
     * --isolation-level read_committed: 读已提交数据
     *
     * kafka-console-consumer.sh --bootstrap-server  master:9092,node1:9092,node2:9092 --isolation-level read_committed --from-beginning --topic tran
     *
     */

  }

}
